<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ajax extends Admin_Controller{
	public function __construct(){
		parent::__construct();
	}

	public function showChat(){
		$ip = $this->input->post('ipaddress');
		$pathChat = APPPATH.'../assets/chat/';
		$response = array();
		if($ip != ''){
			$fileChat = $ip.'.txt';
			$fullPath = $pathChat.$fileChat;
			if(file_exists($fullPath)){
				$lines = file($fullPath);
			}
			$text= array();
			$fp = fopen($fullPath, 'w');
			fwrite($fp, "");
			fclose($fp);
			foreach ($lines as $line_num => $line){
				if($line_num >= $state){
					$line = $lineTmp = str_replace("\n", "", $line);
					$text[] = $line; 
					$arrLineTmp = explode("|", $lineTmp);
					$arrLineTmp[3] = 0;
					$lineTmp = implode("|", $arrLineTmp);
					$fp = fopen($fullPath, 'a');
					fwrite($fp, $lineTmp."\n");
					fclose($fp);
				}
			}
			$response['text'] = $text; 
		}
		echo json_encode($response);
	}

	public function chat(){
	    $pathChat = APPPATH.'../assets/chat/';
	    $ip = $this->input->post('ipaddress');
		$fileChat = $ip.'.txt';
		$fullPath = $pathChat.$fileChat;
		$time = date('Y-m-d H:i:s');
		// $nickname = 'Admin';
		$message = $this->input->post('message');
		// $nickname = htmlentities(strip_tags($nickname));
		$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
		$message = htmlentities(strip_tags($message));
		if($message != "\n"){
			if(preg_match($reg_exUrl, $message, $url)) {
				$message = preg_replace($reg_exUrl, '<a href="'.$url[0].'" target="_blank">'.$url[0].'</a>', $message);
			}
			// $content = "<span>". $nickname . "</span>" . $message = str_replace("\n", " ", $message) . "\n";
			$message = str_replace("\n", " ", $message);
			// $content = '<li class="left clearfix"><span class="chat-img pull-left"><img src="'.base_url()."public/templates/home/images/admin.gif".'" alt="Admin Avatar" class="img-circle" /></span><div class="chat-body clearfix"><div class="header"><small class=" text-muted"><span class="glyphicon glyphicon-time"></span>'.$time.'</small><strong class="pull-right primary-font">'.$nickname.'</strong></div><p>'.$message.'</p></div></li>'. "\n";
			$content = '1|'.$time.'|'.$message.'|1'."\n";
			$fp = fopen($fullPath, 'a');
			fwrite($fp,$content);
			fclose($fp);
		}
	}
}